package com.example.testappwidget.widgetprovider

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.graphics.Point
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.View
import android.widget.RemoteViews
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import com.example.testappwidget.R
import com.example.testappwidget.ui.activity.MainActivity
import com.example.testappwidget.utils.LogUtil
import com.example.testappwidget.utils.StringUitl
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *Author: chinadragon
 *Time: 2024/4/7
 */
class StateWidget: AppWidgetProvider() {
    var count = 0

    companion object{
        const val TAG = "StateWidget ---> "
    }

    override fun onUpdate(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray?) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)
        LogUtil.i(TAG, "回调 onUpdate context == null : ${context == null}")
        appWidgetIds?.let {
            LogUtil.i(TestWidget.TAG, "回调 onUpdate appWidgetIds.size = ${it.size}")
            for ((index, item) in it.withIndex()){
                LogUtil.i(TAG,"回调 onUpdate appWidgetIds：${item}")
                val point = getWidgetSize(context!!, appWidgetManager!!, item)
                LogUtil.i(TAG," StateWidget 实际宽高 px point = $point")
            }
//
//            it.map {item ->
//                LogUtil.i(TAG,"回调 onUpdate appWidgetIds：${item}")
//            }
        }

        if (context == null){
            return
        }

        val scope = CoroutineScope(Dispatchers.Default)
        scope.launch {
            // 在后台线程中执行网络请求
//            val result = makeNetworkRequest()
            withContext(Dispatchers.Main){

                val updatetime = "更新时间:${StringUitl.timeStamp2DateYMDHMS(System.currentTimeMillis())}"

                val views = RemoteViews(context.packageName, R.layout.layout_state_widget_view_medium1)
                views.setTextViewText(R.id.tvMyStateValue, "开心")
                views.setTextViewText(R.id.tvFriendSateValue, "欢喜")
                views.setTextViewText(R.id.tvUpdateTime, updatetime)

//                views.setViewVisibility(R.id.myEmo,View.GONE)
                views.setViewVisibility(R.id.myEmoViewFlipper,View.VISIBLE)


                val frames = arrayOf(R.drawable.battery1,R.drawable.battery2, R.drawable.battery3)
//                val animationDrawable = AnimationDrawable()

                views.removeAllViews(R.id.myEmoViewFlipper)
                for(frame in frames){
//                    val bitmapDrawable = ContextCompat.getDrawable(context, frame)
//                    bitmapDrawable?.let { animationDrawable.addFrame(it,100) }

                    val batteryView = RemoteViews(context.packageName,R.layout.item_battery)
                    batteryView.setImageViewResource(R.id.imgBattery, frame)

//                    val drawable: Drawable? = ContextCompat.getDrawable(context, frame)
//                    drawable?.let {
//                        batteryView.setImageViewBitmap(R.id.imgBattery, it.toBitmap())
//                    }

                    views.addView(R.id.myEmoViewFlipper, batteryView)
                }
//
//                animationDrawable.isOneShot = false

//                views.addView()

//                views.setImageViewResource(R.id.myEmo, R.drawable.battery_list)
//                views.setImageViewBitmap(R.id.myEmo, animationDrawable.toBitmap(200,100,null))
//                animationDrawable.start()



                val drawable: Drawable? = ContextCompat.getDrawable(context, R.drawable.medium_appwidget_bg_shape2)
                drawable?.let {
                    views.setImageViewBitmap(R.id.ivBackground, it.toBitmap())
                }


                //为AppWidget设置点击事件的响应，启动显示电池信息详情的activity
                val startActivityIntent = Intent(context, MainActivity::class.java)
                val bundle = Bundle()
                bundle.putString(MainActivity.key_mystate, "搬砖")
                bundle.putString(MainActivity.key_friendstate, "听歌")
                bundle.putString(MainActivity.key_updatetime, updatetime)
//                startActivityIntent.putExtra(MainActivity.key_mystate,"搬砖")
//                startActivityIntent.putExtra(MainActivity.key_friendstate,"听歌")
//                startActivityIntent.putExtra(MainActivity.key_updatetime, updatetime)
//                startActivityIntent.putExtras(bundle)
                val pendingIntent = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R){
                    PendingIntent.getActivity(context,0,startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT)
                }else{
                    PendingIntent.getActivity(context,0,startActivityIntent, PendingIntent.FLAG_MUTABLE)
                }
                views.setOnClickPendingIntent(R.id.ivBackground, pendingIntent)

                appWidgetManager?.updateAppWidget(appWidgetIds, views)
            }
        }
    }

    override fun onDeleted(context: Context?, appWidgetIds: IntArray?) {
        super.onDeleted(context, appWidgetIds)
        LogUtil.i(TAG, "回调 onDeleted")

    }

    private fun getWidgetSize(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int): Point {
        // 获取AppWidget的大小
        val appWidgetProviderInfo = appWidgetManager.getAppWidgetInfo(appWidgetId)
        val appWidgetOptions = appWidgetManager.getAppWidgetOptions(appWidgetId)
        val minWidth = appWidgetProviderInfo.minWidth
        val minHeight = appWidgetProviderInfo.minHeight
        var width = minWidth
        var height = minHeight

        // 如果API版本支持，则从AppWidgetOptions中获取实际大小
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            width = appWidgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)
            height = appWidgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
        }

        LogUtil.i(TAG," StateWidget 实际宽高 dp width = $width ， height = $height")

        // 将DP转换为像素
        val displayMetrics = context.resources.displayMetrics
        return Point(pxFromDp(displayMetrics, width), pxFromDp(displayMetrics, height))
    }

    private fun pxFromDp(displayMetrics: DisplayMetrics, dp: Int): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), displayMetrics)
            .toInt()
    }

}